package com.mgq.netty.c11;

import com.mgq.netty.chat.message.LoginRequestMessage;
import com.mgq.netty.chat.protocol.MessageCodecShare;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * @author MaGuangQi
 * 测试自定义协议编码器
 * @date 2021-12-07 10:32
 **/
public class TestMessageCodec {

    public static void main(String[] args) throws Exception {
        LoggingHandler LOG_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecShare MESSAGE_CODEC = new MessageCodecShare();
        EmbeddedChannel channel = new EmbeddedChannel();
        //最大长度1024(此处假设,应该是4位表示的最大数+前面的长度)
        //长度字段偏移量12
        //长度4字节
        //调整偏移量 0
        //从0开始读,不跳
        //引入LengthFieldBasedFrameDecoder解决半包问题
        channel.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 12, 4, 0, 0));
        channel.pipeline().addLast(LOG_HANDLER);
        channel.pipeline().addLast(MESSAGE_CODEC);
        //测试编码与解码
        //构造一个ByteBuf
        LoginRequestMessage message=new LoginRequestMessage("zhangsan","123");
        message.setSequenceId(1);
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        //encode方法本身就是netty给我们传入ByteBuff,我们把内容写入,就构造一个buffer
        new MessageCodec().encode(null,message,buffer);
        int length=buffer.readableBytes();
        //模拟半包现象,发送部分内容,会报错,解决办法,引入长度字段帧解码器
        ByteBuf slice = buffer.slice(0, 100);
        ByteBuf slice2 = buffer.slice(100,length-100);
       //channel.writeInbound(buffer);
        channel.writeInbound(slice);
        //记得引用计数+1
        slice.retain();
        channel.writeInbound(slice2);

    }
}
